package com.yzy.util;

import com.yzy.exception.VisionException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Component
public class ExcelFileParseUtils {

    private static final String XLSX_EXCEL_FORMAT = ".xlsx";

    private static final String XLS_EXCEL_FORMAT = ".xls";

    public static Sheet parseExcelOnDatafile(String excelPath, int sheetIndex) throws IOException {
        FileInputStream inputStream = null;
        try {
            if (!excelPath.contains(".") || (!XLSX_EXCEL_FORMAT.equals(excelPath.substring(excelPath.lastIndexOf("."))) && !XLS_EXCEL_FORMAT.equals(excelPath.substring(excelPath.lastIndexOf("."))))) {
                throw new VisionException(HttpStatus.FORBIDDEN, "添加失败，文件格式不正确！", excelPath);
            }
            File file = new File(excelPath);
            inputStream = new FileInputStream(file);
            Workbook workbook;
            if (XLSX_EXCEL_FORMAT.equals(excelPath.substring(excelPath.lastIndexOf(".")))) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                workbook = new HSSFWorkbook(inputStream);
            }
            try {
                return workbook.getSheetAt(sheetIndex);
            } catch (Exception e) {
                throw new VisionException(HttpStatus.FORBIDDEN, "工作表不存在，解析失败！");
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}
